﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Components.Security;
using System.Collections;

namespace ASPNETVN.PORTAL.Modules.SECURITY.Controls
{
    public partial class AddEditRole : AddEditItemControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.ButtonUpdate = btnUpdate;
            this.ButtonDelete = btnDelete;
            this.ButtonCancel = btnCancel;

            this.Update += new EventHandler(AddEditRole_Update);
            this.Delete += new EventHandler(AddEditRole_Delete);
            base.OnInit(e);
        }

        void AddEditRole_Update(object sender, EventArgs e)
        {
            Role role = new Role();
            if (this.ItemID > 0)
            {
                role = Role.Load(this.ItemID);
            }

            role.PortalID = Global.PortalID;
            role.Name = txtName.Text;
            role.Description = txtDescription.Text;

            // Insert.
            if (this.ItemID == 0)
            {
                this.ItemID = role.Insert();
            }
            // Update.
            else
            {
                role.Update();
            }

            // Go back.
            this.ReturnToReferrerPage();
        }

        void AddEditRole_Delete(object sender, EventArgs e)
        {
            if (this.ItemID > 0)
            {
                Role.DeleteRole(this.ItemID);
                // Go back.
                this.ReturnToReferrerPage();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (this.ItemID > 0)
                {
                    GridViewUsers.DataSource = User.SelectByRoleID(this.ItemID);
                    GridViewUsers.DataBind();

                    Role role = Role.Load(this.ItemID);
                    if (role != null)
                    {
                        txtName.Text = role.Name;
                        txtDescription.Text = role.Description;
                    }
                }
                else
                {
                    btnDelete.Visible = false;
                }
            }
        }

       
        protected void GridViewUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "RemoveUser")
            {
                User.RemoveRole(Int32.Parse(e.CommandArgument.ToString()), this.ItemID);
                GridViewUsers.DataSource = User.SelectByRoleID(this.ItemID);
                GridViewUsers.DataBind();
            }
        }
    }
}